home *** CD-ROM | disk | FTP | other *** search
- Path: drivel.ics.uci.edu!ucivax!gateway
- From: klefstad@catalina.ICS.UCI.EDU ("Raymond Klefstad, Ph.D.")
- Subject: Composite functions in C++ - an example
- Message-ID: <9602061650.aa09526@paris.ics.uci.edu>
- Newsgroups: comp.lang.c++,ics.141,ics.145a,ics.147
- Date: 7 Feb 96 00:54:45 GMT
-
-
-
- /*
- A collegue of mine who does research in Machine Learning asked me
- how to do composition of functions in C++. My solution uses a
- combination of operator overloading, pure virtual functions, and
- inheritance. I thought other C++ users might find it interesting.
- The domain and range must be the same for these functions for
- composition to make sense. This particular program composes
- functions mapping double into double, but you could modify it
- for other types including mapping lists into lists for LISP-like
- composition. Check out the polymorphic integrate function used
- as an example user of functions.
-
- Raymond Klefstad, Ph.D. U.C. Irvine, 2/6/96
- */
-
- #include <iostream.h>
-
-
- typedef double (*doublefn)(double);
-
- struct function
- {
- virtual double operator () (double d) = 0;
- };
-
- struct primitive : function
- {
- doublefn fp;
- primitive(doublefn f) : fp(f) {}
- double operator () (double d) {return fp(d);}
- };
-
- struct composite : function
- {
- function &fp, &gp;
- composite(function &f, function &g) : fp(f), gp(g) {}
- double operator () (double d) {return fp(gp(d));}
- };
-
-
- // Approximate an integral of f from lower to upper
-
- double integrate(function &f, double lower, double upper)
- {
- double step = (upper-lower)/100000;
- double sum = 0;
- for (double x = lower; x <= upper; x += step)
- sum += f(x);
- return sum * step;
- }
-
-
- // Some test functions
-
- double f(double d)
- {
- return d*d;
- }
-
- double g(double d)
- {
- return d+2;
- }
-
-
- void main()
- {
- const double Low = 0.0;
- const double High = 2.0;
-
- primitive f1 = f, g1 = g;
- composite fg(f1, g1);
- composite gf(g1, f1);
- composite fggf(fg, gf);
- composite gffg(gf, fg);
-
- cout << integrate(f1, Low, High) << endl;
- cout << integrate(g1, Low, High) << endl;
- cout << integrate(fg, Low, High) << endl;
- cout << integrate(gf, Low, High) << endl;
- cout << integrate(fggf, Low, High) << endl;
- cout << integrate(gffg, Low, High) << endl;
- }
-